import org.codehaus.groovy.grails.commons.GrailsClassUtils as GCU
import groovy.text.SimpleTemplateEngine
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.scaffolding.*
import org.springframework.mock.web.MockServletContext
import org.springframework.core.io.Resource;

/*
 * Usage: grails GeneratePicker YourDomainClassName
 */

Ant.property(environment:"env")                             
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"    

includeTargets << new File ( "${grailsHome}/scripts/Package.groovy" )
    
target ('default': "Generates a \"picker\" panel for a domain class") {
	depends( checkVersion, packageApp )
	typeName = "Domain Class"
	promptForName()
	generate()
}            

target(generate:"The implementation target") {
	                                     
	rootLoader.addURL(classesDir.toURL())
	def beans = new grails.spring.WebBeanBuilder().beans {
		resourceHolder(org.codehaus.groovy.grails.commons.spring.GrailsResourceHolder) {
			this.resources = "file:${basedir}/grails-app/domain/**/*.groovy"
		}
		grailsResourceLoader(org.codehaus.groovy.grails.commons.GrailsResourceLoaderFactoryBean) {
			grailsResourceHolder = resourceHolder
		}
		def pluginResources = [] as Resource[]
		if(new File("${basedir}/plugins/*/plugin.xml").exists()) {
		    pluginResources = "file:${basedir}/plugins/*/plugin.xml"
		}

		pluginMetaManager(org.codehaus.groovy.grails.plugins.DefaultPluginMetaManager, pluginResources) 
		grailsApplication(org.codehaus.groovy.grails.commons.DefaultGrailsApplication.class, ref("grailsResourceLoader"))
	}
                                                    
	appCtx = beans.createApplicationContext()     
	appCtx.servletContext = new MockServletContext()
	grailsApp = appCtx.grailsApplication  
	

	grailsApp.initialise()
	def name = args.trim()
	name = name.indexOf('.') > -1 ? name : GCU.getClassNameRepresentation(name)
	def domainClass = grailsApp.getDomainClass(name)
	
	if(!domainClass) {
		println "Domain class not found in grails-app/domain, trying hibernate mapped classes..."		
		try {
			def config = new GrailsRuntimeConfigurator(grailsApp, appCtx)  
			appCtx = config.configure(appCtx.servletContext)     			
		} catch(Exception e) {
			println e.message
			e.printStackTrace()
		}
		domainClass = grailsApp.getDomainClass(name)  
	}

	if(domainClass) {
		def file = new File("src/templates/scaffolding/picker.gsp")
		def propertyName = domainClass.name
		propertyName = domainClass.name[0].toLowerCase() + domainClass.name[1..(domainClass.name.size()-1)]
		def binding = [domainClass:domainClass, propertyName:propertyName]
		def writable = new SimpleTemplateEngine().createTemplate(file).make(binding)
		new File("${propertyName}Picker.gsp").write(writable.toString())
		event("StatusFinal", ["Finished generation of ${propertyName}Picker.gsp}"])
	} else {
		event("StatusFinal", ["No domain class found for name ${name}. Please try again and enter a valid domain class name"])
	}
}
